<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover" class="search-wrapper">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
            <el-form-item label="栏目名称" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入栏目名称" clearable @keyup.enter="handleQuery" :prefix-icon="Search" />
            </el-form-item>
            <el-form-item label="栏目类型" prop="categoryType">
              <el-select v-model="queryParams.categoryType" placeholder="栏目类型" clearable class="w-[180px]">
                <el-option v-for="dict in categoryTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover" class="table-wrapper">
      <template #header>
        <el-row :gutter="10" class="mb-[8px]">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['cms:category:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">
              {{ isExpandAll ? '折叠' : '展开' }}
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        ref="categoryTableRef"
        v-loading="loading"
        :data="categoryList"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="isExpandAll"
        border
        highlight-current-row
        class="category-table"
      >
        <el-table-column prop="title" label="栏目名称" min-width="260" show-overflow-tooltip>
          <template #default="scope">
            <span :class="['category-title', { 'is-parent': scope.row.parentId === '0' }]">
              {{ scope.row.title }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="上级栏目" prop="parentId" width="180">
          <template #default="scope">
            <span v-if="scope.row.parentId == '0'" class="text-primary">顶级栏目</span>
            <span v-else-if="scope.row.parentId === undefined" class="text-muted">无</span>
            <span v-else class="text-primary">{{ getParentName(scope.row.parentId) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="访问路径" width="180"></el-table-column>
        <el-table-column prop="categoryType" label="栏目类型" width="100">
          <template #default="scope">
            <dict-tag :options="categoryTypeOptions" :value="scope.row.categoryType" />
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center"></el-table-column>
        <el-table-column prop="isShow" label="状态" width="100">
          <template #default="scope">
            <dict-tag :options="cms_is_show" :value="scope.row.isShow" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="200">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="链接类型" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="row.linkType == 1 ? 'warning' : ''">
              {{ row.linkType == 1 ? '外部链接' : '内部链接' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="链接地址" align="center" show-overflow-tooltip min-width="200">
          <template #default="{ row }">
            <template v-if="row.linkType === 1">
              <el-link :href="row.linkUrl" :target="row.linkTarget" type="primary">
                {{ row.linkUrl }}
              </el-link>
            </template>
            <template v-else>
              <span class="text-gray-500">{{ getMenuPath(row.menuId) }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="200">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['cms:category:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button v-hasPermi="['cms:category:add']" link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['cms:category:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="700px" append-to-body destroy-on-close draggable :close-on-click-modal="false">
      <el-form ref="categoryFormRef" :model="form" :rules="rules" label-width="100px" class="category-form">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级栏目">
              <el-tree-select
                v-model="form.parentId"
                :data="categoryOptions"
                :props="{ label: 'title', value: 'id', children: 'children' }"
                value-key="id"
                placeholder="选择上级栏目"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="栏目名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入栏目名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="访问路径" prop="path">
              <el-input v-model="form.path" placeholder="请输入访问路径">
                <template #prepend>/</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="栏目类型" prop="categoryType">
              <el-select v-model="form.categoryType" placeholder="请选择栏目类型">
                <el-option v-for="dict in categoryTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isShow">
              <el-radio-group v-model="form.isShow">
                <el-radio v-for="dict in cms_is_show" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="链接类型" prop="linkType">
              <el-radio-group v-model="form.linkType" @change="handleLinkTypeChange">
                <el-radio :label="0">内部链接</el-radio>
                <el-radio :label="1">外部链接</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="页面模板" prop="template">
              <el-select v-model="form.template" placeholder="请选择页面模板" clearable>
                <el-option v-for="template in templateOptions" :key="template" :label="template" :value="template" />
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="form.linkType === 1">
            <el-col :span="24">
              <el-form-item label="外链地址" prop="linkUrl">
                <el-input v-model="form.linkUrl" placeholder="请输入外部链接地址">
                  <template #prepend>
                    <el-select v-model="linkProtocol" style="width: 100px">
                      <el-option label="http://" value="http://" />
                      <el-option label="https://" value="https://" />
                    </el-select>
                  </template>
                </el-input>
                <div class="form-tips">外部链接需要包含 http:// 或 https:// 前缀</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="打开方式" prop="linkTarget">
                <el-radio-group v-model="form.linkTarget">
                  <el-radio label="_self">当前窗口</el-radio>
                  <el-radio label="_blank">新窗口</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="24">
            <el-form-item label="SEO标题" prop="seoTitle">
              <el-input v-model="form.seoTitle" placeholder="请输入SEO标题" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="SEO关键词" prop="seoKeywords">
              <el-input v-model="form.seoKeywords" placeholder="请输入SEO关键词" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="SEO描述" prop="seoDescription">
              <el-input v-model="form.seoDescription" type="textarea" placeholder="请输入SEO描述" />
            </el-form-item>
          </el-col>
      
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
   
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="buttonLoading" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Category" lang="ts">
import { listCategory, getCategory, delCategory, addCategory, updateCategory, getTemplatesList } from '@/api/cms/category';
import { CategoryVO, CategoryQuery, CategoryForm, CategoryType } from '@/api/cms/category/types';
import { handleTree } from '@/utils/ruoyi';
import { Search } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable, cms_is_show } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'cms_is_show'));

// 栏目类型选项
const categoryTypeOptions = ref([
  { label: '文章栏目', value: CategoryType.ARTICLE },
  { label: '单页栏目', value: CategoryType.PAGE }
]);

const categoryTableRef = ref<ElTableInstance>();
const categoryList = ref<CategoryVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const categoryOptions = ref<CategoryVO[]>([]);
const isExpandAll = ref(true);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const queryFormRef = ref<ElFormInstance>();
const categoryFormRef = ref<ElFormInstance>();

// 查询参数
const queryParams = ref<CategoryQuery>({
  title: undefined,
  categoryType: undefined
});

// 表单参数
const initFormData: CategoryForm = {
  parentId: '0',
  title: '',
  path: '',
  categoryType: CategoryType.ARTICLE,
  template: '',
  sort: 0,
  isShow: '2',
  linkType: 0,
  menuId: undefined,
  linkUrl: '',
  linkTarget: '_self',
  isNav: '0',
  navType: '1',
  menuIds: []
};

const form = ref<CategoryForm>({ ...initFormData });

const rules = ref({
  title: [{ required: true, message: '栏目名称不能为空', trigger: 'blur' }],
  path: [
    { required: true, message: '访问路径不能为空', trigger: 'blur' },
    { pattern: /^[a-z0-9\-\/]+$/, message: '只能包含小写字母、数字、横杠和斜杠', trigger: 'blur' }
  ],
  categoryType: [{ required: true, message: '请选择栏目类型', trigger: 'change' }],
  sort: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }],
  isShow: [{ required: true, message: '请选择状态', trigger: 'change' }],
  seoTitle: [{ required: true, message: '请输入SEO标题', trigger: 'change' }],
  seoKeywords: [{ required: true, message: '请输入SEO关键词', trigger: 'change' }],
  seoDescription: [{ required: true, message: '请输入SEO描述', trigger: 'change' }],
  linkUrl: [
    {
      validator: (rule: any, value: string) => {
        if (form.value.linkType === 1) {
          if (!value) {
            return Promise.reject('外部链接地址不能为空');
          }
          if (!/^https?:\/\/.+/.test(value)) {
            return Promise.reject('请输入有效的URL地址');
          }
        }
        return Promise.resolve();
      },
      trigger: 'blur'
    }
  ],
  menuId: [
    {
      validator: (rule: any, value: string) => {
        if (form.value.linkType === 0 && !value) {
          return Promise.reject('请选择关联栏目');
        }
        return Promise.resolve();
      },
      trigger: 'change'
    }
  ]
});

/** 查询栏目列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listCategory(queryParams.value);
    const list = res.rows || [];
    // 构建树形数据
    const treeData = handleTree(list, 'id', 'parentId');
    // 添加顶级栏目
    categoryList.value = [
      {
        id: '0',
        title: '顶级栏目',
        parentId: '-1', // 使用-1表示最顶层
        children: treeData
      }
    ];
  } finally {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  form.value.isShow = '1';
  categoryFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(categoryList.value, isExpandAll.value);
};

/** 展开/折叠所有 */
const toggleExpandAll = (data: CategoryVO[], status: boolean) => {
  data.forEach((item) => {
    categoryTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) {
      toggleExpandAll(item.children, status);
    }
  });
};

/** 获取上级栏目名称 */
const getParentName = (parentId: string) => {
  // 如果是顶级栏目的子栏目，返回"顶级栏目"
  if (parentId === '0') {
    return '顶级栏目';
  }

  const findParent = (list: CategoryVO[]): string => {
    for (const item of list) {
      if (item.id === parentId) {
        return item.title;
      }
      if (item.children && item.children.length > 0) {
        const name = findParent(item.children);
        if (name) return name;
      }
    }
    return '';
  };
  return findParent(categoryList.value);
};

/** 新增按钮操作 */
const handleAdd = async (row?: CategoryVO) => {
  reset();
  form.value.isShow = '1';
  const res = await listCategory();
  const list = res.rows || [];
  // 构建树形数据
  const treeData = handleTree(list, 'id', 'parentId');
  // 添加顶级栏目选项
  categoryOptions.value = [
    {
      id: '0',
      title: '顶级栏目',
      children: treeData
    }
  ];
  if (row && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = '0'; // 确保默认选中顶级栏目
  }
  dialog.visible = true;
  dialog.title = '添加栏目';
};

/** 修改按钮操作 */
const handleUpdate = async (row: CategoryVO) => {
  reset();
  const res = await getCategory(row.id);
  form.value = res.data;
  const response = await listCategory();
  const list = response.rows || [];
  // 构建树形数据
  const treeData = handleTree(list, 'id', 'parentId');
  // 添加顶级栏目选项
  categoryOptions.value = [
    {
      id: '0',
      title: '顶级栏目',
      children: treeData
    }
  ];
  dialog.visible = true;
  dialog.title = '修改栏目';
};

/** 提交按钮 */
const submitForm = () => {
  categoryFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.linkType === 1 && form.value.linkUrl) {
        if (!form.value.linkUrl.startsWith('http')) {
          form.value.linkUrl = linkProtocol.value + form.value.linkUrl;
        }
      }

      if (form.value.id) {
        await updateCategory(form.value);
      } else {
        await addCategory(form.value);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: CategoryVO) => {
  await proxy?.$modal.confirm('是否确认删除名称为"' + row.title + '"的数据项？');
  await delCategory(row.id);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

// 添加相关变量和方法
const linkProtocol = ref('https://');

// 处理链接类型变化
const handleLinkTypeChange = (type: number) => {
  if (type === 0) {
    form.value.linkUrl = '';
    form.value.linkTarget = '_self';
  } else {
    form.value.menuId = undefined;
  }
};

// 获取栏目路径
const getMenuPath = (menuId: string) => {
  const findMenu = (list: CategoryVO[], id: string): CategoryVO | undefined => {
    for (const item of list) {
      if (item.id === id) {
        return item;
      }
      if (item.children) {
        const found = findMenu(item.children, id);
        if (found) return found;
      }
    }
    return undefined;
  };

  const menu = findMenu(categoryList.value, menuId);
  return menu ? `/${menu.path}` : '';
};

// 模板选项
const templateOptions = ref<string[]>([]);

/** 获取模板列表 */
const getTemplateList = async () => {
  try {
    const res = await getTemplatesList();
    templateOptions.value = res.data;
  } catch (error) {
    console.error('获取模板列表失败:', error);
  }
};

onMounted(() => {
  getList();
  getTemplateList();
});
</script>

<style lang="scss" scoped>
.search-wrapper {
  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}

.table-wrapper {
  margin-top: 8px;
}

.category-table {
  margin-top: 8px;

  :deep(.el-table__row) {
    .category-title {
      &.is-parent {
        font-weight: bold;
        color: var(--el-color-primary);
      }
    }
  }

  :deep(.el-table__row--level-0) {
    font-weight: bold;
    background-color: var(--el-fill-color-light);
  }
}

.category-form {
  :deep(.el-form-item__content) {
    .el-select,
    .el-tree-select {
      width: 100%;
    }

    .el-input-number {
      width: 100%;
    }
  }
}

// 暗黑模式适配
html.dark {
  .category-table {
    :deep(.el-table__row--level-0) {
      background-color: var(--el-bg-color-overlay);
    }
  }
}

// 动画效果
.dialog-fade-enter-active {
  animation: dialog-fade-in 0.3s;
}

.dialog-fade-leave-active {
  animation: dialog-fade-out 0.3s;
}

@keyframes dialog-fade-in {
  0% {
    transform: translate3d(0, -20px, 0);
    opacity: 0;
  }
  100% {
    transform: translate3d(0, 0, 0);
    opacity: 1;
  }
}

@keyframes dialog-fade-out {
  0% {
    transform: translate3d(0, 0, 0);
    opacity: 1;
  }
  100% {
    transform: translate3d(0, -20px, 0);
    opacity: 0;
  }
}

.text-muted {
  color: var(--el-text-color-secondary);
  font-style: italic;
}

.text-primary {
  color: var(--el-color-primary);
}

.form-tips {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}
</style>
